#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
script name: __init__.py
Created on 2020/2/16 19:52 by PyCharm
@author: fujianjian
"""
from threading import current_thread

from .. import find_seed_queue, wsite_thread_pool, db
from .find_seed import OstrichCrawler
from .find_msite import ActressCrewler


def launch_seed_crawler(app):
    wsite_thread_pool.submit(listen_seed_signal, app)
    print('launch seed crawler success', current_thread().getName(), current_thread().ident)


def listen_seed_signal(app):
    print('listen seed signal')
    while True:
        try:
            signal = find_seed_queue.get(block=True)
            print('the signal', str(signal))
            wsite_thread_pool.submit(crawl_seed_task, app, signal)
            print('=' * 15, 'listening search task')
        except Exception as exce:
            print('listen signal error', exce)


def crawl_seed_task(app, production):
    print('crawl seed  task %s' % production, current_thread().getName(), current_thread().ident)
    seed_list = OstrichCrawler().crawler_seed(production.name)
    if seed_list:
        for s in seed_list:
            s.product_id = production.id

        with app.app_context():
            db.session.add_all(seed_list)
            production.seed_count = len(seed_list)
            production.has_search = True
            db.session.commit()

    print('crawl seed  task', current_thread().getName(), current_thread().ident)
